#!/usr/bin/python

import os
import sys

qp_script = 'xyzPossum.m'

def check_software_exist():
    global qp_script
    
    matlab_exists = os.system('/usr/local/bin/matlab -nodisplay > __temp << EOF')
    os.system('rm __temp')

    qp_script_exists = os.path.exists(qp_script)

    if matlab_exists != 0:
        print 'matlab not found on your system'
        sys.exit(1)
        
    if not qp_script_exists:
        print 'matlab script', qp_script, 'not found on your system'
        sys.exit(1)


def qp(filename):
    check_software_exist()
    
    if not os.path.exists(filename):
        print "file", filename, "doesn't exists!"
        sys.exit(1)

    qp_file = open(qp_script)    
    qp_file_lines = qp_file.readlines()
    qp_file.close()

    new_qp_file = open('__qp_script.m', 'w')

    qp_file_lines[0] = "Sequence =  '" + filename + "';\n"

    new_qp_file.writelines(qp_file_lines)

    new_qp_file.close()

    os.system('/usr/local/bin/matlab -nodisplay < __qp_script.m  > __results')

    os.system('rm __qp_script.m')

    result_file = open('__results')
    result_lines = result_file.readlines()
    result_file.close()

    os.system('rm __results')

    final_result = []

    for i in xrange(-5, -1):
        line = (result_lines[i])[2:]
        line = line.strip()
        all = line.split(' ')
        row = []

        for j in xrange(len(all)):
            if all[j]:
                row.append(all[j])

        for k in xrange(len(row)):
            row[k] = (float)(row[k])

        final_result.append(row)

    return final_result
 
if __name__ == '__main__':
    ans = qp(sys.argv[1])

    for row in ans:
        for col in row:
            print '%.3f' % (col),
        print 
